package com.hmall.item.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.item.constants.EsConstants;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.domain.po.ItemDoc;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@RequiredArgsConstructor
public class UpdateIndexDocListener {
    private final IItemService iItemService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstants.INDEX_DOC_QUEUE_NAME),
            exchange = @Exchange(MqConstants.INDEX_DOC_EXCHANGE_NAME),
            key = {MqConstants.INDEX_DOC_KEY}
    ))
    public void ListenUpdateIndexDoc(List<Long> itemIds) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(HttpHost.create(EsConstants.ESADDR)));
        //TODO 修改索引库的信息
        List<ItemDoc> docs = BeanUtil.copyToList(iItemService.queryItemByIds(itemIds), ItemDoc.class);
        BulkRequest request = new BulkRequest();
        docs.forEach(
                doc->{
                    request.add(new IndexRequest(EsConstants.INDEX)
                            .id(doc.getId())
                            .source(JSONUtil.toJsonStr(doc), XContentType.JSON));
                }
        );
        client.bulk(request, RequestOptions.DEFAULT);
    }

}
